package cn.com.cdb.ldms.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Oracle布尔值类型处理器
 * 支持处理NUMBER(1)、CHAR(1) 'Y'/'N'、CHAR(1) '1'/'0'等多种Oracle布尔表示方式
 */
public class OracleBooleanTypeHandler extends BaseTypeHandler<Boolean> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType) throws SQLException {
        // 统一转换为NUMBER(1)格式存储
        ps.setInt(i, parameter ? 1 : 0);
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object value = rs.getObject(columnName);
        return convertToBoolean(value);
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object value = rs.getObject(columnIndex);
        return convertToBoolean(value);
    }

    @Override
    public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object value = cs.getObject(columnIndex);
        return convertToBoolean(value);
    }

    private Boolean convertToBoolean(Object value) {
        if (value == null) {
            return false;
        }

        // 处理NUMBER类型
        if (value instanceof Number) {
            return ((Number) value).intValue() == 1;
        }

        // 处理字符串类型
        if (value instanceof String) {
            String strValue = ((String) value).trim().toUpperCase();
            return "Y".equals(strValue) || "1".equals(strValue) || "TRUE".equals(strValue);
        }

        // 其他类型尝试转换为布尔值
        return Boolean.parseBoolean(value.toString());
    }
}